//
//  BindPhoneViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/27.
//

#import "BindPhoneViewController.h"
#import "YMCountDown.h"
#import "CountDownBtn.h"
#import "LoginTextField.h"
#import "AreaChooseViewController.h"
#import "BindMobileManager.h"
#import "AreaListModel.h"
#import "SendSmsCodeManager.h"
#import "NSString+NumberVerify.h"


@interface BindPhoneViewController ()<UITextFieldDelegate,YMCountDownDelegate,NoDoubleButtonDelegate,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)LoginTextField *phoneTF;
@property(nonatomic,strong)LoginTextField *codeTF;
@property(nonatomic,strong)CountDownBtn *countDownBtn;
@property(nonatomic,strong)YMCountDown *countDown;
@property(nonatomic,strong)UIButton *selBtn;
@property(nonatomic,strong)UIButton *areaBtn;
@property(nonatomic,strong)BindMobileManager *bindMobileManager;
@property(nonatomic,strong)AreaListModel *areaModel;
@property(nonatomic,strong)SendSmsCodeManager *sendCodeManager;
@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIButton *sureBtn;

@end

@implementation BindPhoneViewController

-(BindMobileManager *)bindMobileManager{
    if(!_bindMobileManager){
        _bindMobileManager = [[BindMobileManager alloc]init];
        _bindMobileManager.delegate = self;
    }
    return _bindMobileManager;
}

-(SendSmsCodeManager *)sendCodeManager{
    if(!_sendCodeManager){
        _sendCodeManager = [[SendSmsCodeManager alloc]init];
        _sendCodeManager.delegate = self;
    }
    return _sendCodeManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.type == 1){
        [self popGestureClose];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(self.type == 1){
        [self popGestureOpen];
    }
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    
    if(self.type == 1){
        self.customNavigationBar.leftButton.hidden = YES;
    }
    
    CGFloat w282 = [DeviceUtils getAdaptedWidthForDesignWidth:282 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(w282 > self.currentAvailableHeight){
        w282 = self.currentAvailableHeight;
    }
    
    UIImageView *bgImageView = [[UIImageView alloc]init];
    bgImageView.image = [UIImage imageNamed:@"mine_login_topbg"];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(w282);
    }];
    self.bgImageView = bgImageView;
    
    CGFloat w240 = [DeviceUtils getAdaptedWidthForDesignWidth:240 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(isIPAD){
        if(w240 > (self.currentAvailableHeight-39-52-52-14-52-49-70-70)){
            w240 = self.currentAvailableHeight-39-52-52-14-52-49-70-70;
        }
    }else{
        if(w240 > (self.currentAvailableHeight-39-52-52-14-52-kWFit(49)-70-70)){
            w240 = self.currentAvailableHeight-39-52-52-14-52-kWFit(49)-70-70;
        }
    }
    
    __weak typeof(self)self_weak_  = self;
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = JPUIFontPingFangSCMedium(28);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.text = @"绑定手机号";
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@39);
        make.top.mas_equalTo(w240);
        make.left.mas_equalTo(@32);
    }];
    self.titleLabel = titleLabel;
    
    self.areaModel = [[AreaListModel alloc]init];
    self.areaModel._id = @"1";
    self.areaModel.areaId = @"86";
    self.areaModel.areaName = @"中国(China)";
    
    self.phoneTF = [[LoginTextField alloc]init];
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.phoneTF placeHolderStr:@"请输入你的手机号"];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,70,52)];
    CGFloat a_w = [self getStringWidthWithText:@"+86" font:JPUIFontInterMedium(15) viewHeight:46];
    self.areaBtn = [[UIButton alloc]initWithFrame:CGRectMake(0,3,a_w+16,46)];
    [self.areaBtn setTitle:@"+86" forState:UIControlStateNormal];
    [self.areaBtn setTitleColor:KFontBlackColor forState:UIControlStateNormal];
    self.areaBtn.titleLabel.font = JPUIFontInterMedium(15);
    [self.areaBtn addTarget:self action:@selector(areaBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:self.areaBtn];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(53.5,20,0.5,12)];
    line.backgroundColor = UIColorHex(0xE5E5E5);
    [leftView addSubview:line];
    self.phoneTF.leftView = leftView;
    self.phoneTF.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@24);
        make.right.mas_equalTo(@-24);
        make.top.mas_equalTo(titleLabel.mas_bottom).offset(52);
        make.height.mas_equalTo(@52);
    }];
    
    self.codeTF = [[LoginTextField alloc]init];
    self.codeTF.keyboardType = UIKeyboardTypeDefault;
    [self.codeTF placeHolderStr:@"请输入验证码"];
    CGFloat c_w = [self getStringWidthWithText:@"获取验证码" font:JPUIFontPingFangSCRegular(13) viewHeight:46];
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, c_w+16,52)];
    self.countDownBtn = [[CountDownBtn alloc]initWithFrame:CGRectMake(2,3,c_w+14,46)];
    [self.countDownBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.countDownBtn setTitleColor:KThemeColor forState:UIControlStateNormal];
    self.countDownBtn.titleLabel.font = JPUIFontPingFangSCRegular(13);
    self.countDownBtn.delegate = self;
    [self.countDownBtn addTarget:self action:@selector(countDownClick) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:self.countDownBtn];
    self.codeTF.rightView = rightView;
    self.codeTF.rightViewMode = UITextFieldViewModeAlways;
    self.codeTF.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,8,52)];
    self.codeTF.leftViewMode = UITextFieldViewModeAlways;
    self.codeTF.delegate = self;
    [self.view addSubview:self.codeTF];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@24);
        make.right.mas_equalTo(@-24);
        make.top.mas_equalTo(self_weak_.phoneTF.mas_bottom).offset(14);
        make.height.mas_equalTo(@52);
    }];
    if (!self.countDown) {
        self.countDown = [[YMCountDown alloc] init];
        self.countDown.delegate = self;
    }
    
   
    UIButton *sureBtn = [[UIButton alloc]init];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = JPUIFontPingFangSCMedium(15);
    if(isIPAD){
        sureBtn.layer.cornerRadius = 49/2.0;
    }else{
        sureBtn.layer.cornerRadius = kWFit(49)/2.0;
    }
    sureBtn.layer.masksToBounds = YES;
    sureBtn.backgroundColor = KThemeColor;
    sureBtn.ym_acceptEventInterval = 2.0;
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@24);
        if(isIPAD){
            make.height.mas_equalTo(@49);
        }else{
            make.height.mas_equalTo(kWFit(49));
        }
        make.right.mas_equalTo(@-24);
        make.top.mas_equalTo(self_weak_.codeTF.mas_bottom).offset(70);
    }];
    self.sureBtn = sureBtn;
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           // 获取当前可用宽度并更新布局
           self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
           self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
           self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat w282 = [DeviceUtils getAdaptedWidthForDesignWidth:282 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(w282 > self.currentAvailableHeight){
                w282 = self.currentAvailableHeight;
            }
            [self.bgImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(w282);
            }];
            CGFloat w240 = [DeviceUtils getAdaptedWidthForDesignWidth:240 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(w240 > (self.currentAvailableHeight-39-52-52-14-52-49-70-70)){
                w240 = self.currentAvailableHeight-39-52-52-14-52-49-70-70;
            }
            [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(w240);
            }];
            __weak typeof(self)self_weak_  = self;
            [self.phoneTF mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self_weak_.titleLabel.mas_bottom).offset(52);
            }];
            [self.codeTF mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self_weak_.phoneTF.mas_bottom).offset(14);
            }];
            [self.sureBtn mas_updateConstraints:^(MASConstraintMaker *make){
                make.top.mas_equalTo(self_weak_.codeTF.mas_bottom).offset(70);
            }];
        });
    }
}


#pragma mark - 确定绑定
-(void)sureBtnClick{
    
    if(self.phoneTF.text.length == 0){
        [JPProgressHUD showMsg:@"请输入手机号"];
        return;
    }
    
    BOOL isValid = [self.phoneTF.text parseForPhoneNumberWithCountryCode:self.areaModel.areaId];
    if(!isValid){
        [JPProgressHUD showMsg:@"手机号格式不正确"];
        return;
    }
    
    if(self.codeTF.text.length == 0){
        [JPProgressHUD showMsg:@"请输入验证码"];
        return;
    }
    
    self.bindMobileManager.phone = [NSString stringWithFormat:@"%@%@",self.areaModel.areaId,self.phoneTF.text];
    NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
    if(phone&&[self.sendCodeManager.mobile isEqualToString:phone]){
        [JPProgressHUD showMsg:@"手机号与之前绑定手机相同"];
        return;
    }
    self.bindMobileManager.mobileCode = self.codeTF.text;
    if(self.type == 1){
        if(self.userModel.unionid){
            self.bindMobileManager.unionid = self.userModel.unionid;
        }else{
            NSString *unionid = [[NSUserDefaults standardUserDefaults]objectForKey:@"unionid"];
            self.bindMobileManager.unionid = unionid?unionid:@"";
        }
    }else{
        //正常绑定 如果登录是微信的 也要传
        NSString *unionid = [[NSUserDefaults standardUserDefaults]objectForKey:@"unionid"];
        self.bindMobileManager.unionid = unionid?unionid:@"";
    }
    if(self.userModel.userId){
        self.bindMobileManager.userId = self.userModel.userId;
    }else{
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        if(userId){
            self.bindMobileManager.userId = userId;
        }else{
            self.bindMobileManager.userId = @"";
        }
    }
    [self.bindMobileManager loadData];
    
}

#pragma mark - 区号选择
-(void)areaBtnClick{
    AreaChooseViewController *vc = [[AreaChooseViewController alloc]init];
    vc.selAreaModel = self.areaModel;
    [self.navigationController pushViewController:vc animated:YES];
    __weak typeof(self)self_weak_ = self;
    [vc setSelBlock:^(AreaListModel * _Nonnull areaModel) {
        self_weak_.areaModel = areaModel;
        [self_weak_.areaBtn setTitle:[NSString stringWithFormat:@"+%@",areaModel.areaId] forState:UIControlStateNormal];
    }];
}

#pragma mark - 获取验证码
-(void)countDownClick{
    if(self.phoneTF.text.length == 0){
        [JPProgressHUD showMsg:@"请输入手机号"];
        return;
    }
    
    BOOL isValid = [self.phoneTF.text parseForPhoneNumberWithCountryCode:self.areaModel.areaId];
    if(isValid){
        self.sendCodeManager.mobile = [NSString stringWithFormat:@"%@%@",self.areaModel.areaId,self.phoneTF.text];
        NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
        if(phone&&[self.sendCodeManager.mobile isEqualToString:phone]){
            [JPProgressHUD showMsg:@"手机号与之前绑定手机相同"];
            return;
        }
        [self.sendCodeManager loadData];
    }else{
        [JPProgressHUD showMsg:@"手机号格式不正确"];
    }
}

-(void)BtnClick:(UIButton *)btn{
    [self countDownClick];
}

#pragma mark - 倒计时代理 JPCountryCodeChoiceControllerDelegate
- (void)countDownWillFire:(YMCountDown *)countDown{
    self.countDownBtn.userInteractionEnabled = NO;
}

-(void)countDown:(YMCountDown *)countDown runningTime:(NSTimeInterval)runningTime{
    NSString *str = [NSString stringWithFormat:@"%is",(int)runningTime];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self.countDownBtn setTitle:str forState:UIControlStateNormal];
    }];

}

-(void)countDown:(YMCountDown *)countDown didStopInTime:(NSTimeInterval)time{
     self.countDownBtn.userInteractionEnabled = YES;
    [self.countDownBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.sendCodeManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [self.countDown fire];
    }
    
    if([manager isEqual:self.bindMobileManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        MineUserModel *model = [MineUserModel mj_objectWithKeyValues:dic[@"data"]];
        //登录后绑定
        if(model.userId){
            [[NSUserDefaults standardUserDefaults]setObject:model.userId forKey:@"userId"];
        }
        
        if(model.phone){
            [[NSUserDefaults standardUserDefaults]setObject:model.phone forKey:@"phone"];
        }
        
        if(model.nickname){
            [[NSUserDefaults standardUserDefaults]setObject:model.nickname forKey:@"nickname"];
        }
        if(model.avatar){
            [[NSUserDefaults standardUserDefaults]setObject:model.avatar forKey:@"avatar"];
        }
        if(model.sex){
            [[NSUserDefaults standardUserDefaults]setObject:model.sex forKey:@"sex"];
        }
        if(model.introduction){
            [[NSUserDefaults standardUserDefaults]setObject:model.introduction forKey:@"introduction"];
        }
        if(model.goldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:model.goldNumber forKey:@"goldNumber"];
        }
        
        if(model.signCount){
            [[NSUserDefaults standardUserDefaults]setObject:model.signCount forKey:@"signCount"];
        }
        if(model.token){
            [[NSUserDefaults standardUserDefaults]setObject:model.token forKey:@"access_token"];
        }
        if(self.type == 1){
            [[NSNotificationCenter defaultCenter]postNotificationName:@"loginSuccess" object:model];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"phoneUpdate" object:model.phone];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
